package com.example.learnvitamio.live

import android.content.DialogInterface
import android.net.Uri
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import com.example.learnvitamio.R
import com.example.learnvitamio.base.BaseActivity
import com.example.learnvitamio.databinding.ActivityLiveBinding
import io.vov.vitamio.MediaPlayer
import io.vov.vitamio.Vitamio
import java.text.SimpleDateFormat
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*

class LiveActivity : BaseActivity<ActivityLiveBinding>() {

    companion object{
        //顶部和底部的panel自动隐藏时间5s
        private const val AUTO_HIDE_TIME = 5000L
    }

    private var url:String? = ""
    private var title:String? = ""
    private var mCount = 0
    private val maxCount = 5
    private val mHandler = Handler(Looper.getMainLooper())

    override fun ActivityLiveBinding.initBinding() {
        url = intent.getStringExtra("url")
        title = intent.getStringExtra("title")
        Log.d("LiveActivity:","路径:$url  标题：$title")
        mBinding.ivBack.setOnClickListener {
            finish()
        }
        tvTitle.text = title
        tvTime.text = now()
        //初始化Vitamio
        initVitamio()
        rootLayout.setOnClickListener {
            if (llTopLayout.visibility == View.VISIBLE || llBottomLayout.visibility == View.VISIBLE){
                llTopLayout.visibility = View.GONE
                llBottomLayout.visibility = View.GONE
                return@setOnClickListener
            }
            if (mBinding.surfaceView.isPlaying){//正在播放显示暂停图
                ivPlayPause.setImageResource(R.drawable.ic_player_pause)
            }else{
                ivPlayPause.setImageResource(R.drawable.ic_player_play)
            }
                llTopLayout.visibility = View.VISIBLE
            llBottomLayout.visibility = View.VISIBLE
            //显示panel时，5秒后自动隐藏
            mHandler.postDelayed({
                llTopLayout.visibility = View.GONE
                llBottomLayout.visibility = View.GONE
            }, AUTO_HIDE_TIME)
        }
        ivPlayPause.setOnClickListener {
            if (mBinding.surfaceView.isPlaying){
                mBinding.surfaceView.stopPlayback()
                mBinding.ivPlayPause.setImageResource(R.drawable.ic_player_play)
                return@setOnClickListener
            }
            mBinding.ivPlayPause.setImageResource(R.drawable.ic_player_pause)
            mBinding.surfaceView.setVideoURI(Uri.parse(url))
            mBinding.surfaceView.setOnPreparedListener {
                surfaceView.start()
            }
        }
    }

    //初始化Vitamio逻辑
    private fun initVitamio(){
        Vitamio.isInitialized(applicationContext)
        mBinding.surfaceView.setVideoURI(Uri.parse(url))
        mBinding.surfaceView.setOnPreparedListener {
            mBinding.surfaceView.start()
        }
        //播放出错事件监听
        mBinding.surfaceView.setOnErrorListener(object :MediaPlayer.OnErrorListener{
            override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
                Log.e("LiveActivity","播放出错...$mCount 次")
                //播放出错，会尝试播放5次，超过5次不成功则返回弹窗
                if (mCount>maxCount){
                    AlertDialog.Builder(this@LiveActivity)
                        .setMessage("播放出错...")
                        .setPositiveButton("OK") {
                                dialog, which -> {finish()} }.setCancelable(false).show()
                }else{
                    mBinding.surfaceView.stopPlayback()
                    mBinding.surfaceView.setVideoURI(Uri.parse(url))
                }
                mCount ++
                return false
            }
        })

        //正在缓冲监听
        mBinding.surfaceView.setOnInfoListener(object :MediaPlayer.OnInfoListener{
            override fun onInfo(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
                when(what){
                    //正在缓冲
                    MediaPlayer.MEDIA_INFO_BUFFERING_START -> {
                        Log.d("LiveActivity","正在缓冲...")
                        mBinding.rlLoadingLayout.visibility = View.VISIBLE
                    }
                    //缓冲完成，并有声音先出以及下载有变化的时候
                    MediaPlayer.MEDIA_INFO_BUFFERING_END
                        ,MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING,
                    MediaPlayer.MEDIA_INFO_DOWNLOAD_RATE_CHANGED-> {
                        mBinding.rlLoadingLayout.visibility = View.GONE
                    }
                }
                return false
            }
        })
    }

    private fun now():String{
        val calendar = Calendar.getInstance()
        val sdf = SimpleDateFormat("yyy-MM-dd HH:mm:ss")
        return sdf.format(calendar.time)
    }

    override fun onStop() {
        super.onStop()
        mCount = 0
        if (mBinding.surfaceView != null){
            mBinding.surfaceView.stopPlayback()
        }
    }
}